package game_frame

import (
	"gamesdk/common/log"
	"gamesdk/common/queue"
	"gamesdk/inter"

	"sync"
	"time"

	"gamesdk/clock"
)

var MAX_WAIT_TIME = 20 * time.Millisecond

func NewAIManager(room *Room) *AIManager {
	defer log.Trace()()
	aiManager := &AIManager{
		room: room,
		//clock: clock.NewClock(),
	}
	aiManager.robotQueue = queue.NewQueue(1024)
	for n := 1000; n >= 100; n-- {
		ok := aiManager.robotQueue.Push(n, MAX_WAIT_TIME)
		if !ok {
			log.Error("%v", ok)
			panic("error")
		}
	}

	return aiManager
}

type AIManager struct {
	isOpen     bool         //是否启用
	clock      *clock.Clock //定时器
	robots     sync.Map
	room       *Room
	robotQueue *queue.Queue
}

// //添加定时器
// func (this *AIManager) AddTimer(actionInterval time.Duration, jobFunc func()) (job clock.Job, ok bool) {
// 	defer log.Trace()()
// 	//添加定时
// 	return this.clock.AddJobWithInterval(actionInterval*time.Millisecond, jobFunc)
// }

// //添加重复定时器
// func (this *AIManager) AddTimerRepeat(interval time.Duration, actionMax uint64, jobFunc func()) (jobScheduled clock.Job, inserted bool) {
// 	defer log.Trace()()
// 	return this.clock.AddJobRepeat(interval*time.Millisecond, actionMax, jobFunc)
// }

func (this *AIManager) AddRobot(userId int64, user inter.AIUserInter) {
	defer log.Trace()()
	this.robots.Store(userId, user)
}

//机器人退出
func (this *AIManager) DelRobot(userId int64) {
	defer log.Trace()()
	_, ok := this.robots.Load(userId)
	if ok {
		this.robots.Delete(userId)
	}
}

/*
*遍历所有机器人
 */
func (this *AIManager) Traverse(f TraverseUserFunc) {
	defer log.Trace()()
	function := func(key, value interface{}) bool {
		if value != nil {
			user, ok := value.(*User)
			if !ok {
				log.Warn("user is not *User")
			} else {
				return f(user)
			}
		}
		return true
	}
	this.robots.Range(function)
}
